import 'package:cloud_medicine/components/address_edit&new.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:flutter/material.dart';

class EditAddress extends StatefulWidget {
  final num id;
  final String name;
  final String address;
  final num phone;
  EditAddress(
      {Key key,
      @required this.id,
      @required this.address,
      @required this.name,
      @required this.phone})
      : super(key: key);

  @override
  _EditAddressState createState() => _EditAddressState();
}

class _EditAddressState extends State<EditAddress> {
  TextEditingController addressController = new TextEditingController();
  TextEditingController nameController = new TextEditingController();
  TextEditingController phoneController = new TextEditingController();

  // bool _isSaved = false;
  bool _loading = false;
  DateTime lastPopTime;

  Future<Null> _init() async {
    setState(() {
      _loading = true;
    });
    await Future.delayed(Duration(milliseconds: 100), () {
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    });
    return;
  }

  @override
  void initState() {
    super.initState();
    _init();
  }

  @override
  void dispose() {
    super.dispose();
    addressController.dispose();
    nameController.dispose();
    phoneController.dispose();
  }

  _childLayout() {
    if (_loading) {
      return Center(
        child: Container(
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      return AddressEditAndNew(
        addressController: addressController,
        nameController: nameController,
        phoneController: phoneController,
        saveInfoAndCommit: _saveInfoAndCommit,
        oldaddress: widget.address,
        oldname: widget.name,
        oldphone: widget.phone.toString(),
        id: 2,
        addressid: widget.id,
      );
    }
  }

  _saveInfoAndCommit() {
    //TODO:传给后端，返回页面时自动替换新地址
    Navigator.pop(context);
  }

  _popPage() {
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (lastPopTime == null ||
            DateTime.now().difference(lastPopTime) > Duration(seconds: 1)) {
          //两次点击间隔超过1秒则重新计时
          lastPopTime = DateTime.now();
          openAlertDialog(context, _popPage, '确认退出编辑，一旦退出，一切将不予保存');
          return new Future.value(false);
        }
        return new Future.value(true);
      },
      child: Scaffold(
        backgroundColor: Colors.grey[300],
        appBar: AppBar(
          centerTitle: true,
          title: Text('编辑收货地址'),
        ),
        body: _childLayout(),
      ),
    );
  }
}
